package com.bhkj.pdjhforotherapp.core.readsfzprint;

import android.annotation.SuppressLint;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.widget.TextView;
import android.widget.Toast;

import com.bhkj.pdjhforotherapp.R;
import com.bhkj.pdjhforotherapp.common.Contact;
import com.bhkj.pdjhforotherapp.common.bean.JhResultBean;
import com.bhkj.pdjhforotherapp.common.bean.RePrintBean;
import com.bhkj.pdjhforotherapp.common.callback.CallbackManager;
import com.bhkj.pdjhforotherapp.common.callback.IGlabolCallback;
import com.bhkj.pdjhforotherapp.common.parse.GsonProvider;
import com.bhkj.pdjhforotherapp.common.utils.NetIpUtils;
import com.bhkj.pdjhforotherapp.common.utils.Tools;
import com.bhkj.pdjhforotherapp.core.base.BaseActivity;
import com.bhkj.pdjhforotherapp.core.printutilspdj.Bills;
import com.bhkj.pdjhforotherapp.core.printutilspdj.UsbPrintManager;
import com.bhkj.pdjhforotherapp.core.printutilspdj.Utils;
import com.bhkj.pdjhforotherapp.core.tip.TipActivity;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.CacheDiskStaticUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.reader.sdk.CardReader;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import net.lemonsoft.lemonhello.LemonHello;
import net.lemonsoft.lemonhello.LemonHelloAction;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.disposables.Disposable;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

@SuppressWarnings("rawtypes")
public class JHDetailActivity extends BaseActivity {
    private GifImageView mGiv;
    private int mCountForTime = 120;//倒计时
    private TextView mTvTimer;//倒计时文字显示
    private String title;
    private String num;
    private GifDrawable gifDrawable;
    //    private IDCardReaderClient sfzBuilder;
    private Timer timer;
    private TimerTask timerTask;
    private Disposable saveSelectedYwDisposable;
    private String windowName;
    private boolean isPrintLog;
    private JhResultBean jhResultBean;
    private boolean isIdNumRead;//身份证是否已经读取成功

    @Override
    public int getLayoutId() {
        return getResources().getBoolean(R.bool.isQhj) ? R.layout.activity_jhdetail : R.layout.activity_jhdetail_pjq;
    }

    @SuppressLint("NewApi")
    @Override
    public void initView() {
        getWindow().setLayout(1600, 1000);
//        String idNum = "13092919911112421" + Math.round(Math.random() * 10);
//        saveSelectedYwToServer("测试", idNum);
//        findViewById(R.id.iv_jh_detail_logo).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });

        mGiv = findViewById(R.id.giv_jh_detail);
        mTvTimer = findViewById(R.id.tv_jh_detail_timer);
        findViewById(R.id.iv_jh_detail_logo).setOnClickListener(v -> finish());
        SwitchCompat sc = findViewById(R.id.sc_id_read);
        sc.setOnCheckedChangeListener((buttonView, isChecked) -> isPrintLog = !isChecked);
    }

    @Override
    public void initData() {
        UsbPrintManager.getInstance().initPrint();
//        readSfzReader();
        initCountDown();
        CallbackManager.getInstance().addCallback(Contact.CLOSE_READ_ID, o -> finish());
        CallbackManager.getInstance().addCallback(Contact.TIP_REPRINT, o -> {
            RePrintBean rePrintBean = (RePrintBean) o;
            Bills.printSmallTicket(UsbPrintManager.getInstance().getUsbDriver(), rePrintBean.getTitle() + "\n\n", rePrintBean.getWindowName(),
                    rePrintBean.getNum(), rePrintBean.getQueueNum(), rePrintBean.getQueueTime(), 0); // 排队票据
            finish();
        });

    }

    private void initCountDown() {
        if (gifDrawable != null && !gifDrawable.isRecycled()) {
            gifDrawable.recycle();
        }
        gifDrawable = (GifDrawable) mGiv.getDrawable();
        if (gifDrawable != null) {
            gifDrawable.setLoopCount(65535);
        }
        //2分钟后自动超时返回上一页
        if (timer == null) {
            timer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    mCountForTime--;
                    runOnUiThread(() -> mTvTimer.setText("倒计时" + mCountForTime + "秒"));
                    if (mCountForTime % 2 == 0 && !isIdNumRead) {
//                        sfzBuilder.readIDCard();
                        CardReader.getInstance(getApplication()).readId(readerBean -> {
                            runOnUiThread(() -> {
                                if (isPrintLog) {
                                    Toast.makeText(getApplicationContext(), readerBean.getMessage(), Toast.LENGTH_SHORT).show();
                                }

                                //读取身份证信息
                                if (ObjectUtils.isNotEmpty(readerBean.getIdNum()) && ObjectUtils.isNotEmpty(readerBean.getName())) {
                                    if (saveSelectedYwDisposable != null) {
                                        EasyHttp.cancelSubscription(saveSelectedYwDisposable);
                                    }
                                    isIdNumRead = true;
                                    cancelReadTask(false);
                                    if (UsbPrintManager.getInstance().showPrintDeviceStatus()) {
                                        saveSelectedYwToServer(readerBean.getName(), readerBean.getIdNum());
                                    }
                                }
                            });

                        });

                    }
//                            到0秒后自动关闭界面返回上一页
                    if (mCountForTime == 0) {
                        finish();
                    }

                }
            };
        }

        timer.schedule(timerTask, 0, 1000);
    }

    /**
     * 关闭读身份证模块
     *
     * @param isFinish true 关闭 false 不关闭
     */
    private void cancelReadTask(boolean isFinish) {
        if (timer != null) {
            timer.cancel();
            if (isFinish) {
                timer = null;
            }
        }
        if (timerTask != null) {
            timerTask.cancel();
            if (isFinish) {
                timerTask = null;
            }
        }
    }

    /**
     * 读取身份证信息
     */
    private void readSfzReader() {

//        if (ActivityUtils.isActivityAlive(this)) {
//            sfzBuilder = IDCardReaderClient.build()
//                    .setContext(this)
//                    .setReaderResultCallback(res -> runOnUiThread(() -> {
//                        runOnUiThread(() -> {
//                            if (isPrintLog) {
//                                Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT).show();
//                            }
//                        });
//                        //读取身份证信息
//                        ReaderResultBean readerResultBean = GsonUtils.fromJson(res, ReaderResultBean.class);
//                        if (readerResultBean.getCode() == 0 && readerResultBean.getData() != null) {
//                            if (saveSelectedYwDisposable != null) { EasyHttp.cancelSubscription(saveSelectedYwDisposable); }
//                            isIdNumRead = true;
//                            cancelReadTask(false);
//                            if (usbPrintManager.showPrintDeviceStatus()){
//                                saveSelectedYwToServer(readerResultBean.getData().getChineseName(), readerResultBean.getData().getPassNumCh());
//                            }
//                        }
//                    })).builder();
//        }
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void saveSelectedYwToServer(String name, String idNum) {
        if (!NetworkUtils.isConnected()) {
            ToastUtils.showShort(R.string.tip_connect_net_content);
            return;
        }
        showLoading();
        String queueBusiness = "";
        if (getIntent() != null) {
            queueBusiness = getIntent().getStringExtra(Contact.SURE_YW);
        }
        try {
            name = URLEncoder.encode(name, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        net(queueBusiness, name, idNum);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void net(String queueBusiness, String name, String idNum) {
        String deviceId = Tools.getDeviceId();
        String windowType = Contact.COMMON_WINDOW;
        if (getIntent() != null) {
            windowType = getIntent().getStringExtra(Contact.QHTYPE);
        }
        LogUtils.e("ip地址", NetIpUtils.getLocalIPAddress());
        saveSelectedYwDisposable = EasyHttp.post(Contact.SAVE_YW_TO_SERVEr)
                .params("key", deviceId)
                .params("rsa", Tools.encodeRsa(deviceId))
                .params("xm", name)
                .params("sfzhm", idNum)
                .params("deptid", getResources().getString(R.string.deptId))
                .params("windowtype", windowType)
                .params("queueBusiness", queueBusiness)
                .params("ip", NetIpUtils.getLocalIPAddress().getHostAddress())
                .execute(new SimpleCallBack<String>() {
                    @Override
                    public void onError(ApiException e) {
                        LogUtils.i(e.getMessage() + e.getCode());
                        dismissLoading();
                        onErrorTip(getString(R.string.error_again) + e.getMessage());
                    }

                    @Override
                    public void onSuccess(String s) {
//                        LogUtils.i(s);
                        dismissLoading();
                        handleJhSuccessResult(s, idNum);
                    }
                });

    }

    private void handleJhSuccessResult(String s, String idNum) {

        if (TextUtils.isEmpty(s)) {
            TipActivity.create("保存业务数据失败", "空数据", "", idNum, false, this);
            return;
        }
        LogUtils.i(s);
        jhResultBean = GsonProvider.getInstance().getGson().fromJson(s, JhResultBean.class);

        //清除缓存数据
        IGlabolCallback callback = CallbackManager.getInstance().getCallback(Contact.CLEAR_PRINT_DATA);
        if (callback != null) {
            callback.executeCallback("");
        }
        if (jhResultBean != null) {
            //打印小票
            if (jhResultBean.isSuccess()) {

                String repeatPrint = jhResultBean.getDatas().getRepeatPrint();
                if (!ObjectUtils.equals(repeatPrint, "1")) {
                    getStrDataByLanguage(jhResultBean);
                    Bills.printSmallTicket(UsbPrintManager.getInstance().getUsbDriver(), title, windowName, num, String.valueOf(jhResultBean.getDatas().getQueuenum()),
                            String.valueOf(jhResultBean.getDatas().getQueuetime()), 0); // 排队票据
                    SPUtils.getInstance().clear();
                    CacheDiskStaticUtils.remove(Contact.SAVE_YW_SELECTED);
                    //保存选中的业务信息
                    TipActivity.create("取号成功", "您的排队号码:" + num + "\n请您到" + windowName + "窗口排队等候", "", idNum, false, this);
                } else {
                    String printStr = "";
                    JhResultBean.DatasBean datas = jhResultBean.getDatas();
                    if (jhResultBean.getDatas() != null) {
                        printStr = datas.getDeptname() + "-" + datas.getAreaName() + datas.getName() + "-" + datas.getQunumber() +
                                "-" + datas.getQueuenum() + "-" + datas.getQueuetime();
                    }
                    TipActivity.create("已取号", "您的排队号码:" + datas.getQunumber() + "\n请您到" + datas.getAreaName() + datas.getName() + "窗口排队等候", printStr, idNum, true, this);
                }
            } else {
                onErrorTip(jhResultBean.getMessage());
            }
        } else {
            TipActivity.create("保存业务数据失败", "叫号数据返回为空", "", idNum, false, this);
        }
    }

    // 根据系统语言获取测试文本
    private void getStrDataByLanguage(JhResultBean jhResultBean) {
        if (Utils.isZh(this)) {
            title = jhResultBean.getDatas().getDeptname() + "\n\n";
        }
        windowName = jhResultBean.getDatas().getAreaName() + jhResultBean.getDatas().getName();
        num = jhResultBean.getDatas().getQunumber();
    }


    /**
     * 访问保存数据接口出错后的提示对话框，可以接着访问
     * 或者是关闭页面停止访问接口
     *
     * @param tip 提示信息
     */
    private void onErrorTip(String tip) {
        if (ActivityUtils.isActivityAlive(this))
            LemonHello.getErrorHello(tip, tip)
                    .addAction(new LemonHelloAction(getString(R.string.close), (lemonHelloView, lemonHelloInfo, lemonHelloAction) -> {
                        lemonHelloView.hide();
                        mTvTimer.postDelayed(() -> runOnUiThread(() -> finish()), 1000);
                    })).show(this);

    }

    @Override
    protected void onDestroy() {
        UsbPrintManager.getInstance().closePrint();
        if (gifDrawable != null) {
            gifDrawable.recycle();
        }
        cancelReadTask(true);
        IGlabolCallback callback = CallbackManager.getInstance().getCallback(Contact.CLEAR_PRINT_DATA);
        if (callback != null) {
            callback.executeCallback("");
        }
        super.onDestroy();
    }

}
